package com.ocom.payconfig.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ocom.common.entity.payconfig.CouponsItem;
import com.ocom.common.entity.payconfig.EntityReviewOrder;
import com.ocom.common.enums.DataSourceEnum;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.DateUtil;
import com.ocom.common.utils.DateUtils;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.vo.payconfig.BreakCouponsVo;
import com.ocom.common.vo.payconfig.CouponsItemRVo;
import com.ocom.common.vo.payconfig.GrantCouponsVo;
import com.ocom.mysql.aspect.DataSourceAspect;
import com.ocom.payconfig.dao.IDaoCouponsItem;
import com.ocom.payconfig.service.CouponsItemService;
import com.ocom.payconfig.service.ReviewOrderService;
import com.ocom.payconfig.service.VoucherDataService;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 赠券项目
 *
 * @author js
 * @email junshu@qq.com
 * @date 2023-07-14
 */
@Service
public class CouponsItemServiceImpl extends ServiceImpl<IDaoCouponsItem, CouponsItem> implements CouponsItemService {
    @Resource
    private IDaoCouponsItem iDaoCouponsItem;
    @Resource
    private VoucherDataService voucherDataService;
    @Resource
    private ReviewOrderService reviewOrderService;

    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB, companyId = "comId")
    public Boolean updateCouponsItemById(Long comId, int item_id, int status, String breakTime) {
        UpdateWrapper<CouponsItem> update = Wrappers.update();
        update.set("status", status);
        update.set("update_time", new Date());
        if (breakTime != null) {
            update.set("break_time", new Date());
        }
        if (status == 4) {
            update.eq("status", 0);
        }
        update.eq("com_id", comId);
        update.eq("item_id", item_id);
        return this.update(update);
    }

    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB, companyId = "comId")
    public CouponsItem selectCouponsItemByName(Long comId, String couponsItemName) {
        QueryWrapper<CouponsItem> query = Wrappers.query();
        query.eq("com_id", comId);
        query.eq("item_name", couponsItemName);
        query.select("item_name");

        return this.getOne(query);
    }

    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB, companyId = "comId")
    public Result couponsItem(Long comId, int page, int size) {
        PageHelper.startPage(page, size);
        List<CouponsItemRVo> list = iDaoCouponsItem.couponsItem(comId);
        PageInfo<CouponsItemRVo> pageInfo = new PageInfo<>(list);
        Map<String, Object> map = new HashMap<>();
        map.put("list",list);
        map.put("total",pageInfo.getTotal());
        return ResultUtil.success(map);
    }

    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB, companyId = "comId")
    public Boolean CouponsItemUpdateById(Long comId, CouponsItem couponsItem) {
        UpdateWrapper<CouponsItem> updateWrapper = Wrappers.update();
        updateWrapper.eq("com_id", comId);
        updateWrapper.eq("item_id", couponsItem.getItemId());
        updateWrapper.eq("status", 0);

        updateWrapper.set("voucher_type_id", couponsItem.getVoucherTypeId());
        updateWrapper.set("start_date", couponsItem.getStartDate());
        updateWrapper.set("stop_date", couponsItem.getStopDate());
        return this.update(updateWrapper);
    }

    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB, companyId = "comId")
    public Boolean couponsItemByStop(Long comId, int status) {
        QueryWrapper<CouponsItem> query = Wrappers.query();
//        query.eq("com_id", comId);
        query.eq("status", status);
        query.lt("stop_date", new Date());
        query.select("com_id", "item_id", "start_date", "stop_date", "status", "mode");
        List<CouponsItem> couponsItems = this.list(query);
        if (couponsItems == null || couponsItems.size() == 0) {
            return true;
        }
        String orderNo = "";
        for (CouponsItem couponsItem : couponsItems) {
            if (couponsItem.getMode() == 0) {
                orderNo = "M" + couponsItem.getItemId();
            } else {
                orderNo = "A" + couponsItem.getItemId();
            }
            BreakCouponsVo breakCouponsVo = new BreakCouponsVo();
            breakCouponsVo.setComId(couponsItem.getComId().longValue());
            breakCouponsVo.setOrderNo(orderNo);
            voucherDataService.breakCoupons(couponsItem.getComId().longValue(), breakCouponsVo);

            UpdateWrapper<CouponsItem> update = Wrappers.update();
            update.set("status", 2);
            update.set("close_time", new Date());

            update.eq("com_id", comId);
            update.eq("item_id", couponsItem.getItemId());
            this.update(update);
        }
        return true;
    }

    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB, companyId = "comId")
    public Result grantCoupons(Long comId, GrantCouponsVo request) {
        boolean bGrant = voucherDataService.grantCoupons(request.getComId(), request);
        boolean bUpdate = this.updateCouponsItemById(request.getComId(), request.getItemId(), 1, null);

        return ResultUtil.success("bGrant:"+bGrant + "|bUpdate:" + bUpdate);
    }

    private boolean sendReviewOrder(Long comId, GrantCouponsVo request) {
        Date endTime = null;
        String pageParam = null;
        String pageUrl = null;
        try {
//            System.out.println("request==="+request.getStopDate());
//            endTime = Date.from(request.getStopDate().plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant());
//            endTime = Date.from(request.getStopDate().plusDays(1).atZone(ZoneId.systemDefault()).toInstant());
            endTime = DateUtil.addDays(DateUtil.getDate(request.getStopDate(),"yyyy-MM-dd HH:mm:ss"),1);
            pageParam = "{" + MessageFormat.format("orderNo:{0},status{1}", request.getOrderNo(), 0) + "}";
            pageUrl = MessageFormat.format("consume/CouponsVoucher/detail?orderNo={0}&status={1}", request.getOrderNo(), 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        EntityReviewOrder entityReviewOrder = new EntityReviewOrder();
        entityReviewOrder.setComId(request.getComId());
        entityReviewOrder.setThemeNo("couponManual");
        entityReviewOrder.setOrderNo(DateUtils.dateTimeNow() + RandomStringUtils.random(6, false, true));
        entityReviewOrder.setThemeId(String.valueOf(request.getItemId()));
        entityReviewOrder.setBeginTime(new Date());
        entityReviewOrder.setEndTime(endTime);
//        System.out.println("request==="+request.getStopDate());
        entityReviewOrder.setPageUrl(pageUrl);
        entityReviewOrder.setPageParam(pageParam);
        entityReviewOrder.setRemark("");
        entityReviewOrder.setStatus(1);
        entityReviewOrder.setCreateUser(request.getCreateUser());
        boolean bRequest = reviewOrderService.addReviewOrder(entityReviewOrder.getComId(), entityReviewOrder);
        return bRequest;
    }

}
